﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Fadada.FASC.SDK.DotNetCore.Utils
{
    public class DigestUtils
    {
        /// <summary>
        /// SHA256 转换为 Hex字符串
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Sha256Hex(string data, bool toLowerCase = true)
        {
            var bytes = Encoding.UTF8.GetBytes(data);
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(bytes);
                string strHex = ByteArrayToHexString(hash);
                return toLowerCase ? strHex.ToLower() : strHex.ToUpper();
            }
        }

        /// <summary>
        /// SHA256 转换为 Hex字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Sha256Hex(string data, Encoding encoding)
        {
            var bytes = encoding.GetBytes(data);
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(bytes);
                return ByteArrayToHexString(hash);
            }
        }

        /// <summary>
        /// SHA256 转换为 Hex字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string Sha256Hex(byte[] bytes)
        {
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(bytes);
                return ByteArrayToHexString(hash);
            }
        }
        /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
        /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
        /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
        public static string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
            {
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));//.PadRight(3, ' '));
            }

            return sb.ToString().ToLower();
        }
    }
}